from rest_framework import serializers

from apps.questions.models import Label, Reply

from apps.questions.models import Label,Question
from apps.users.models import User
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields=['id','username','avatar']
class QuestionSerializer(serializers.ModelSerializer):
    # labels = serializers.StringRelatedField(many=True)
    # jia
    user_id = serializers.IntegerField()
    user = serializers.StringRelatedField()
    class Meta:
        model = Question
        fields=['id','createtime','labels','reply','replyname','replytime','title',
                'unuseful_count','useful_count','user','visits','content','user_id']

    def create(self, validated_data):
        """
        根据提供的验证过的数据创建并返回一个新的`Author`实例。
        """
        # 将authors 多对多关系的数据从前端传过来的数据中取出，放在authors 中
        labels = validated_data.pop('labels')
        # 将正常的book的数据进行保存，创建Book实例，并通过book 接收
        question = Question.objects.create(**validated_data)
        # 重点中的重点：循环读取authors对象的数据
        for label in labels:
            # 实例化author对象
            label = Label.objects.filter(id=label.id).first()
            # 将多对多的关系添加到book中
            question.labels.add(label)
            # 保存book的多对多关系
            question.save()
        return question


class LabelSerializer(serializers.ModelSerializer):
    questions = QuestionSerializer(many=True)
    # users = UserSerializer(many=True)
    class Meta:
        model=Label

        fields=['id','questions','label_name','desc','baike_url','label_icon','users']

class ReplySeriazlizer(serializers.ModelSerializer):
    problem = serializers.PrimaryKeyRelatedField(queryset=Question.objects.all())
    # problem =serializers.StringRelatedField()
    # problem_id = serializers.IntegerField()
    parent_id = serializers.IntegerField(required=False)
    user_id =serializers.IntegerField()
    class Meta:
        model=Reply
        fields =['id','problem','content','type','parent_id','user_id']
    # def create(self, validated_data):
    #     # 将authors 多对多关系的数据从前端传过来的数据中取出，放在authors 中
    #     labels = validated_data.pop('labels')
    #     # 将正常的book的数据进行保存，创建Book实例，并通过book 接收
    #     question = Question.objects.create(**validated_data)
    #     # 重点中的重点：循环读取authors对象的数据
    #     for label in labels:
    #         # 实例化author对象
    #         label = Label.objects.filter(id=label.id).first()
    #         # 将多对多的关系添加到book中
    #         question.labels.add(label)
    #         # 保存book的多对多关系
    #         question.save()
    #     return question